package com.jack.app

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jack.app.model.AidlMessage
import kotlinx.android.synthetic.main.fragment_preview.*

/**
 *
 *
 * @author Jack 2017-12-21 16:13
 */
class PreviewFragment : Fragment() {
    private var mMsgSender: MessageSender? = null

    private val mConnection = object: ServiceConnection {
        override fun onServiceDisconnected(p0: ComponentName?) {

        }

        override fun onServiceConnected(p0: ComponentName?, binder: IBinder?) {
            mMsgSender = MessageSender.Stub.asInterface(binder)
            val message = AidlMessage()
            message.content = "这是一段测试内容"
            message.from = "来自客户端"
            message.to = "发往服务端"
            mMsgSender?.sendMessage(message)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_preview, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        text.setOnClickListener {
            val intent = Intent(activity, ThirdActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            startActivity(intent)
        }

        btn_test.setOnClickListener {
            val intent = Intent(activity, MessageService::class.java)
            activity.bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        activity.unbindService(mConnection)
    }
}